package net.pws.common.persistence.statement;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.pws.common.persistence.QueryStatementManager;

import org.apache.commons.lang.StringUtils;


/**
 */
public class StatementManagementBean implements QueryStatementManager {
    
    private String namespace = "DEFAULT";
    
    private List queryStatementManagers = new ArrayList();
    
    private Map statementMap = new HashMap();
    
    public String getNamespace() {
        return namespace;
    }
    
    public void setNamespace(String namespace) {
        if (StringUtils.isEmpty(namespace)) {
            throw new IllegalArgumentException("Null or empty namespace is invalid!");
        }
        this.namespace = namespace;
    }
    
    public List getQueryStatementManagers() {
        return queryStatementManagers;
    }
    
    public void setQueryStatementManagers(List queryStatementManagers) {
        this.queryStatementManagers = queryStatementManagers;
    }
    
    public Map getStatementMap() {
        return statementMap;
    }
    
    public void setStatementMap(Map statementMap) {
        this.statementMap = statementMap;
    }
    
    public String getStatementByName(String statementName) {
        String result = (String) statementMap.get(statementName);
        if (StringUtils.isEmpty(result)) {
            for (Iterator iterator = queryStatementManagers.iterator(); iterator.hasNext();) {
                QueryStatementManager queryStatementManager = (QueryStatementManager) iterator.next();
                String statement = queryStatementManager.getStatementByName(statementName);
                if (!StringUtils.isEmpty(statement)) {
                    return statement;
                }
            }
        }
        return result;
    }
    
    public String getStatementByName(String namespace, String statementName) {
        if (StringUtils.isEmpty(namespace)) {
            throw new IllegalArgumentException("Null or empty namespace is invalid!");
        }
        String result = null;
        if (getNamespace().equals(namespace)) {
            result = (String) statementMap.get(statementName);
        }
        if (StringUtils.isEmpty(result)) {
            for (Iterator iterator = queryStatementManagers.iterator(); iterator.hasNext();) {
                QueryStatementManager queryStatementManager = (QueryStatementManager) iterator.next();
                String statement = queryStatementManager.getStatementByName(namespace,
                                                                            statementName);
                if (!StringUtils.isEmpty(statement)) {
                    return statement;
                }
            }
        }
        return result;
    }
}
